package com.my.bbs.service.impl;

import com.my.bbs.dao.MyPostCategoryMapper;
import com.my.bbs.dao.MyPostMapper;
import com.my.bbs.dao.MyUserMapper;
import com.my.bbs.entity.*;
import com.my.bbs.service.MyPostService;
import com.my.bbs.util.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.function.Function;
import java.util.stream.Collectors;

/**
 * @author 86187
 */
@Service
@Transactional(rollbackFor = Exception.class)
public class MyPostServiceImpl implements MyPostService {

    @Resource
    private MyPostCategoryMapper myPostCategoryMapper;
    @Resource
    private MyPostMapper myPostMapper;
    @Resource
    private MyUserMapper myUserMapper;

    @Override
    public int savePost(MyPost myPost) {
        MyUser myUser = myUserMapper.selectByPrimaryKey(myPost.getPublishUserId());
        if (myUser == null || myUser.getUserStatus().intValue() == 1) {
            //账号已被封禁
            return 0;
        }

        MyPostCategory myPostCategory = myPostCategoryMapper.selectByPrimaryKey(myPost.getPostCategoryId());
        if (myPostCategory == null) {
            //分类数据错误
            return 0;
        }
        return myPostMapper.insertSelective(myPost);
    }

    @Override
    public MyPost getMyPostById(Long bbsPostId) {
        return myPostMapper.selectByPrimaryKey(bbsPostId);
    }

    @Override
    public MyPost getMyPostForDetail(Long bbsPostId) {
        MyPost myPost = myPostMapper.selectByPrimaryKey(bbsPostId);
        if (myPost != null) {
            myPost.setPostViews(myPost.getPostViews() + 1);
            myPostMapper.updateByPrimaryKeySelective(myPost);
        }
        return myPost;
    }

    @Override
    public int updateMyPost(MyPost myPost) {
        MyUser myUser = myUserMapper.selectByPrimaryKey(myPost.getPublishUserId());

        if (myUser == null || myUser.getUserStatus().intValue() == 1) {
            //账号已被封禁
            return 0;
        }

        MyPostCategory myPostCategory = myPostCategoryMapper.selectByPrimaryKey(myPost.getPostCategoryId());
        if (myPostCategory == null) {
            //分类数据错误
            return 0;
        }

        return myPostMapper.updateByPrimaryKeySelective(myPost);
    }

    @Override
    public int delMyPost(Long userId, Long postId) {
        MyUser myUser = myUserMapper.selectByPrimaryKey(userId);

        if (myUser == null || myUser.getUserStatus().intValue() == 1) {
            //账号已被封禁
            return 0;
        }

        MyPost myPost = myPostMapper.selectByPrimaryKey(postId);
        // 对象不为空且发帖人为当前登录用户才可以删除
        if (myPost != null && myPost.getPublishUserId().equals(userId)) {
            return myPostMapper.deleteByPrimaryKey(postId);
        }
        return 0;
    }

    @Override
    public PageResult getMyPostPageForIndex(PageQueryUtil pageUtil) {
        //查询帖子数据
        int total = myPostMapper.getTotalPosts(pageUtil);
        List<MyPost> myPostList = myPostMapper.findPostList(pageUtil);
        List<MyPostListEntity> postListEntities = new ArrayList<>();
        //数据格式转换
        if (!CollectionUtils.isEmpty(myPostList)) {
            postListEntities = BeanUtil.copyList(myPostList, MyPostListEntity.class);
            List<Long> userIds = postListEntities.stream().map(MyPostListEntity::getPublishUserId).collect(Collectors.toList());
            //查询user数据
            List<MyUser> myUsers = myUserMapper.selectByPrimaryKeys(userIds);
            if (!CollectionUtils.isEmpty(myUsers)) {
                //封装user数据
                Map<Long, MyUser> bbsUserMap = myUsers.stream().collect(Collectors.toMap(MyUser::getUserId, Function.identity(), (entity1, entity2) -> entity1));
                for (MyPostListEntity myPostListEntity : postListEntities) {
                    if (bbsUserMap.containsKey(myPostListEntity.getPublishUserId())) {
                        //设置头像字段和昵称字段
                        MyUser tempUser = bbsUserMap.get(myPostListEntity.getPublishUserId());
                        myPostListEntity.setHeadImgUrl(tempUser.getHeadImgUrl());
                        myPostListEntity.setNickName(tempUser.getNickName());
                    }
                }
            }
        }
        PageResult pageResult = new PageResult(postListEntities, total, pageUtil.getLimit(), pageUtil.getPage());
        return pageResult;
    }

    @Override
    public List getHotTopicMyPostList() {
        List<MyPost> myPostList = myPostMapper.getHotTopicPostList();
        List<HotTopicPostListEntity> hotTopicPostList = new ArrayList<>();
        if (!CollectionUtils.isEmpty(myPostList)) {
            hotTopicPostList = BeanUtil.copyList(myPostList, HotTopicPostListEntity.class);
        }
        return hotTopicPostList;
    }

    @Override
    public List<MyPost> getMyPostList(Long userId) {
        return myPostMapper.getMyPostList(userId, "all");
    }

    @Override
    public List<MyPost> getRecentPostListByUserId(Long userId) {
        return myPostMapper.getMyPostList(userId, "recent");
    }

    @Override
    public int bannedPost(MyPost post) {
        return myPostMapper.updateByPrimaryKeySelective(post);
    }

    @Override
    public Result unbannedPost(MyPost post) {
        MyPost myPost = myPostMapper.selectByPrimaryKey(post.getPostId());
        MyUser myUser = myUserMapper.selectByPrimaryKey(myPost.getPublishUserId());
        if(myUser.getUserStatus() == (byte) 2){
            return ResultGenerator.genFailResult("解封失败，用户被封");
        }
        myPostMapper.updateByPrimaryKeySelective(post);
        return ResultGenerator.genSuccessResult();
    }

    @Override
    public PageResult getPageBannedPost(PageQueryUtil page) {
        //查询帖子数据
        int total = myPostMapper.getTotalBannedPostCount(page);
        List<MyPost> myPostList = myPostMapper.getPageBannedPost(page);
        List<MyPostListEntity> postListEntities = new ArrayList<>();
        //数据格式转换
        if (!CollectionUtils.isEmpty(myPostList)) {
            postListEntities = BeanUtil.copyList(myPostList, MyPostListEntity.class);
            List<Long> userIds = postListEntities.stream().map(MyPostListEntity::getPublishUserId).collect(Collectors.toList());
            //查询user数据
            List<MyUser> myUsers = myUserMapper.selectByPrimaryKeys(userIds);
            if (!CollectionUtils.isEmpty(myUsers)) {
                //封装user数据
                Map<Long, MyUser> bbsUserMap = myUsers.stream().collect(Collectors.toMap(MyUser::getUserId, Function.identity(), (entity1, entity2) -> entity1));
                for (MyPostListEntity myPostListEntity : postListEntities) {
                    if (bbsUserMap.containsKey(myPostListEntity.getPublishUserId())) {
                        //设置头像字段和昵称字段
                        MyUser tempUser = bbsUserMap.get(myPostListEntity.getPublishUserId());
                        myPostListEntity.setHeadImgUrl(tempUser.getHeadImgUrl());
                        myPostListEntity.setNickName(tempUser.getNickName());
                    }
                }
            }
        }
        PageResult pageResult = new PageResult(postListEntities, total, page.getLimit(), page.getPage());
        return pageResult;
    }
}
